package com.busibuilding.pagination.demo;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.lang.ClassUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Class Name: BaseComparator.java Description:
 * 
 * @author YU Zhipeng
 * @version 1.0
 * @since 1.0 Date: 2009-7-19
 */

public class BaseComparator implements Comparator, Serializable {
	/** * */
	private static final long serialVersionUID = -919057368228216736L;
	private final static Log log = LogFactory.getLog(BaseComparator.class);
	private boolean ascending;
	private String property;

	public BaseComparator() {
	}

	public BaseComparator(boolean ascending, String property) {
		this.ascending = ascending;
		this.property = property;
	}

	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}

	public boolean isAscending() {
		return ascending;
	}

	public void setAscending(boolean ascending) {
		this.ascending = ascending;
	}

	public int compare(Object object1, Object object2) {
		log.info("Sort" + object1.toString() + " " + object2);
		int returnValue = 0;
		if (object1 == null && object2 != null) {
			returnValue = -1;
		} else if (object1 != null && object2 == null) {
			returnValue = 1;
		} else if (object1 == null && object2 == null) {
			returnValue = 0;
		} else if (object1.getClass() == object2.getClass()) {
			try {
				Class objectClass = object1.getClass();
				Field field = objectClass.getDeclaredField(this.property);
				if (!field.isAccessible())
					field.setAccessible(true);
				Class fieldClass = field.getType();
				log.info("----Filed class" + fieldClass);
				List classList = ClassUtils.getAllSuperclasses(fieldClass);
				Class number = Number.class;
				
				if (classList.contains(number)) {
					Number object1Value = (Number) (field.get(object1));
					Number object2Value = (Number) (field.get(object2));
					returnValue = (object1Value.doubleValue() > object2Value
							.doubleValue()) ? 1 : -1;
					if (object1Value.doubleValue() == object2Value
							.doubleValue())
						returnValue = 0;
				
				} else {
					String object1Value = field.get(object1).toString();
					String object2Value = field.get(object2).toString();
					returnValue = object1Value.compareTo(object2Value);
				}
			} catch (Exception e) {
				e.printStackTrace();
				returnValue = 0;
			}
		}
		int ascendingInt = this.ascending ? 1 : -1;
		return ascendingInt * returnValue;
	}
}
